package com.etlmaster.exector.trans.utils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.etlmaster.executor.trans.core.Rule;
import com.etlmaster.executor.utils.DataCollectionUtils;
import com.etlmaster.executor.utils.DpExecutorUtils;
import com.etlmaster.executor.utils.JsonHelper;
import com.etlmaster.jdbc.JdbcTemplate;


/**
 * @author Larry
 * @copyright Larry@etlMaster
 * @since 2017-09-10
 */
public class RowTransUtils {
	public static Map<String,Rule> getRulesByTable(String tableName){
		Map<String,Rule> rules=new HashMap<String,Rule>();
		JdbcTemplate jdbc=new JdbcTemplate();
		String sql=DataCollectionUtils.getProperties("fetchRuleList");
		Map<String,String> table=new HashMap<String,String>();
		table.put("tableName", tableName);
		sql=DpExecutorUtils.variableSubstitution(sql, table);
		List<Map<String,Object>> list=jdbc.queryForList(sql);
		for(Map<String,Object> ruleEntry:list){
			String ruleid=(String)ruleEntry.get("ruleid");
			Rule rule=rules.get(ruleid);
			if(rule==null)
				rule=new Rule(ruleid,(String)ruleEntry.get("sourcetab"),(String)ruleEntry.get("sourcecol"),(String)ruleEntry.get("targettab"),(String)ruleEntry.get("targetcol"));
			String funcType=(String) ruleEntry.get("trans_type");
			Map<String,Object> funcMaps=rule.getFuncMaps();
			if(funcMaps==null){
				funcMaps=new HashMap<String,Object>();
				rule.setFuncMaps(funcMaps);
			}
			Map<String,Object> funcMap=(Map<String, Object>)funcMaps.get(funcType);
			if(funcMap==null){
				funcMap=new HashMap<String,Object>();
				rule.getFuncMaps().put(funcType, funcMap);
			}
			String changeCode=(String) ruleEntry.get("trans_func");
			Map<String,Object> params=(Map<String, Object>) JsonHelper.getInstance().read((String) ruleEntry.get("sql_text"));
			funcMap.put(changeCode, params);
			
			rules.put((String)ruleEntry.get("ruleid"), rule);
		}
		return rules;
	}

}
